package com.ljs.module.controller;

import com.ljs.module.common.DataBean;
import com.ljs.module.common.PathEnum;
import com.ljs.module.entity.common.TreeNode;
import com.ljs.module.entity.template.joint.JointTemplateDto;
import com.ljs.module.service.ScriptParseService;
import com.ljs.module.service.impl.LinkParse;
import com.ljs.module.util.FileUtil;
import com.ljs.module.util.TemplateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/template/joint")
public class BuildJointTemplateController {


    @ResponseBody
    @PostMapping("/update")
    public DataBean updateLinks(@RequestBody JointTemplateDto  dto){
        String params = "";
        if (!StringUtils.isBlank(dto.getLinks())) {
            String noAnnotation = TemplateUtil.removeAnnotation(dto.getLinks());
            LinkParse linkParse = new LinkParse();
            String[] split1 = noAnnotation.split(";");
            for (String s : split1) {
                s += ";";
                if (linkParse.compile(s)) {
                    linkParse.parse(s);
                }
            }
            params = TemplateUtil.getParams(linkParse.getData(), ".js.param");
        }
        return DataBean.success(params);
    }

    @ResponseBody
    @GetMapping("/load")
    public DataBean<JointTemplateDto> loadJoint(String path){
        try {
            DataBean<String[]> jointData = TemplateUtil.getJointData(path, false);
            if (jointData.getData() == null) {
                return DataBean.fail(null);
            }
            String[] data = jointData.getData();
            if (data.length < 3) {
                return DataBean.success(new JointTemplateDto())
                        .setDesc("出错");
            }
            JointTemplateDto jointTemplateDto = new JointTemplateDto();
            if (!StringUtils.isBlank(data[1])) {
                jointTemplateDto.setTemplateCode(data[1]);
            }
            if (!StringUtils.isBlank(data[2])) {
                jointTemplateDto.setJsCode(data[2]);
            }
            String desc = "";
            if (!StringUtils.isBlank(data[0])) {
                jointTemplateDto.setLinks(data[0]);
                String noAnnotation = TemplateUtil.removeAnnotation(data[0]);
                LinkParse linkParse = new LinkParse();
                String[] split1 = noAnnotation.split(";");
                for (String s : split1) {
                    s += ";";
                    if (linkParse.compile(s)) {
                        linkParse.parse(s);
                    }
                }
                String params = TemplateUtil.getParams(linkParse.getData(), ".js.param");
                jointTemplateDto.setParams(params);
                desc += "加载完成\r\n加载引用模板如下\r\n"
                        + linkParse.getData().stream().collect(Collectors.joining("\r\n"))
                        + "\r\n加载参数如下（去重后）\r\n" + params;
            }
            return DataBean.success(jointTemplateDto)
                    .setDesc(desc);
        } catch (Exception ex) {
            return DataBean.fail().setDesc("加载异常\r\n" + ex.getMessage());
        }
    }

    @ResponseBody
    @PostMapping("/run")
    public DataBean runJoint(@RequestBody JointTemplateDto  dto){
        try {
            Map<String, Object> templateKeyORM = TemplateUtil.getTemplateKeyORM(dto);
            DataBean<Map<String, Object>> jsMap = TemplateUtil.getJsMap(dto.getJsCode(), templateKeyORM);
            templateKeyORM.putAll(jsMap.getData());

            ScriptParseService scriptParseService = new ScriptParseService();
            return scriptParseService.action(dto.getPath(), templateKeyORM);
        } catch (Exception ex) {
            return DataBean.fail().setDesc("运行异常\r\n" + ex.getMessage());
        }
    }

    @ResponseBody
    @PostMapping("/compile")
    public DataBean compileJoint(@RequestBody JointTemplateDto  dto){
        StringBuffer stringBuffer = new StringBuffer();
        try {
            Map<String, Object> templateKeyORM = TemplateUtil.getTemplateKeyORM(dto);
            stringBuffer.append("已解析参数\r\n" + templateKeyORM.toString());
            DataBean<Map<String, Object>> jsMap = TemplateUtil.getJsMap(dto.getJsCode(), templateKeyORM);
            if (jsMap.getReasonCode() == 2000) {
                templateKeyORM.putAll(jsMap.getData());
                stringBuffer.append("\r\n\r\n已解析js脚本参数\r\n" + jsMap.getData().toString());
            } else {
                stringBuffer.append(jsMap.getDesc());
                return DataBean.fail().setDesc(stringBuffer.toString());
            }

            ScriptParseService scriptParseService = new ScriptParseService();
            DataBean compile = scriptParseService.compile(dto, templateKeyORM);
            stringBuffer.append("\r\n\r\n解析代码区结果\r\n" + compile.getDesc());
            return compile.setDesc(stringBuffer.toString());
        } catch (Exception ex) {
            return DataBean.fail().setDesc(stringBuffer + "\r\n\r\n运行异常\r\n" + ex.getMessage());
        }
    }

    @ResponseBody
    @PostMapping("/save")
    public void saveJoint(@RequestBody JointTemplateDto  dto){
        FileUtil.writeContent2File(PathEnum.JOINT_TEMPLATE + File.separator + dto.getPath(), dto.getLinks() + TemplateUtil.JOINT_TEMPLATE_SPLIT + "\r\n" + dto.getTemplateCode() + TemplateUtil.JOINT_TEMPLATE_SPLIT + "\r\n" + dto.getJsCode());
    }


    /**
     * 构建升级类
     * @return 操作结果
     */
    @ResponseBody
    @GetMapping("/get/customs")
    public DataBean<List<TreeNode>> getInitCommonTabForType(){
        try {
            List<TreeNode> treeNode = FileUtil.getTreeNode(PathEnum.CUSTOM_TEMPLATE.getPath(),"", ".js", false);
            return DataBean.success(treeNode);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return DataBean.fail().setDesc("");
    }
}
